package com.diandiansong.app.ui.index;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;

import com.diandiansong.app.App;
import com.diandiansong.app.R;
import com.diandiansong.app.entity.CommodityInfoInfo;
import com.diandiansong.app.ui.base.BaseAct;
import com.diandiansong.app.utils.A;
import com.diandiansong.app.utils.Api;
import com.diandiansong.app.widgets.AddAndMinusViewInItem;

import java.util.ArrayList;
import java.util.List;

import diandiansong.library.ui.base.FastListFragment;
import diandiansong.library.utils.BaseEntity;
import diandiansong.library.utils.CCallBack;
import diandiansong.library.utils.ImgLoader;

/**
 * 我的收藏
 */
public class Favorite extends BaseAct {
    public static void start(Context context) {
        Intent starter = new Intent(context, Favorite.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTitle("我的收藏");
        addFragment(new SubFragment());
    }


    public static class SubFragment extends FastListFragment {

        @Override
        protected int getLayoutId() {
            return R.layout.favorite_main;
        }

        @Override
        public int getItemLayoutRes() {
            return R.layout.good_item_add_minus;
        }

        @Override
        public void initView(View rootView) {
            super.initView(rootView);

            cbAll = rootView.findViewById(R.id.cb_all);
            cbAll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mSelected.clear();
                    if (cbAll.isChecked()) {
                        mSelected.addAll(mAdapter.getData());
                    }
                    count();
                    notifyDataSetChanged();
                }
            });
            rootView.findViewById(R.id.do_removeall).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mSelected.size() == 0) {
                        return;
                    }
                    String[] ids = new String[mSelected.size()];
                    for (int i = 0; i < mSelected.size(); i++) {
                        CommodityInfoInfo.Data data = mSelected.get(i);
                        ids[i] = data.getFavoriteId();
                    }
                    onLoading();
                    A.myCollection_del(ids, new CCallBack<BaseEntity>() {
                        @Override
                        public void onSuccess(BaseEntity baseEntity) throws Exception {
                            for (int i = 0; i < mSelected.size(); i++) {
                                CommodityInfoInfo.Data data = mSelected.get(i);
                                mAdapter.remove(data);
                            }
                            mSelected.clear();
                            onLoaded();
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            onLoaded();
                            toast(msg);
                        }
                    });

                }
            });
        }

        @Override
        public void bindItemView(int position, @NonNull View convertView) {
            ImageView check = findViewById(convertView, R.id.iv_cb);
            check.setVisibility(View.VISIBLE);

            final CommodityInfoInfo.Data item = (CommodityInfoInfo.Data) getItem(position);

            if (isSelected(item)) {
                check.setImageResource(R.drawable.img19);
            } else {
                check.setImageResource(R.drawable.img18);
            }

            ImageView iv = findViewById(convertView, R.id.iv_logo);
            ImgLoader.display(iv, item.getImgs());

            fastText(convertView, R.id.tv_1, item.getCommodityName());
            fastText(convertView, R.id.tv_2, item.getCommoditySubtitle());

            String unit = item.getUnit();
            if (unit == null || unit.isEmpty() || unit.equals("/")) {
                unit = "";
            } else {
                unit = "/" + unit;
            }

            fastText(convertView, R.id.tv_3, "￥" + item.getPrice() + unit);

            fastOnClick(convertView, R.id.iv_cb, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateSelected(item);
                    notifyDataSetChanged();
                }
            });

            App.initGoodListAdd(getActivity(), item.getCommodityId(), convertView);
        }

        @Override
        public void onRefresh() {
            mSelected.clear();
            count();
            super.onRefresh();
        }

        /**
         * 滑到底部时调用
         */
        @Override
        protected void loadMore() {
            A.myCollection(mPage, new CCallBack<CommodityInfoInfo>() {
                @Override
                public void onSuccess(CommodityInfoInfo o) throws Exception {
                    List<CommodityInfoInfo.Data> data = o.getData();
                    if (mPage.equals("0")) {
                        mAdapter.setData(data);
                    } else {
                        mAdapter.addAll(data);
                    }
                    if (mAdapter.getDataSize() > 0) {
                        mPage = ((CommodityInfoInfo.Data) getLast()).getCommodityId();
                    }
                    onLoadFinishHasMore(data.size() >= Api.PAGE_SIZE);
                }

                @Override
                public void onFailure(int code, String msg) {
                    onLoadFinishNoMore();
                    toast(msg);
                }
            });
        }

        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            AddAndMinusViewInItem aamvii = view.findViewById(R.id.add_minus);
            CommodityInfoInfo.Data item = (CommodityInfoInfo.Data) getItem(position);
            GoodDetail.start(getActivity(), item.getCommodityId());
        }

        CheckBox cbAll;
        List<CommodityInfoInfo.Data> mSelected = new ArrayList<>();

        private void updateSelected(CommodityInfoInfo.Data single) {
            boolean contain = false;
            for (int i = 0; i < mSelected.size(); ++i) {
                if (single == mSelected.get(i)) {
                    contain = true;
                    mSelected.remove(i);
                    break;
                }
            }
            if (!contain) {
                mSelected.add(single);
            }
            count();
            if (mSelected.size() == mAdapter.getDataSize()) {
                cbAll.setChecked(true);
            } else {
                cbAll.setChecked(false);
            }
        }

        private void count() {
            float money = 0f;
            int count = 0;
            for (int m = 0; m < mAdapter.getData().size(); ++m) {
                for (int i = 0; i < mSelected.size(); ++i) {
                    CommodityInfoInfo.Data item = (CommodityInfoInfo.Data) (mAdapter.getItem(m));
                    if (item == mSelected.get(i)) {
                        money += item.getPriceF() * item.getNum();
                        count++;
                    }
                }
            }
            money = App.readable(money);
        }

        private boolean isSelected(CommodityInfoInfo.Data single) {
            for (int i = 0; i < mSelected.size(); ++i) {
                if (single == mSelected.get(i)) {
                    return true;
                }
            }
            return false;
        }
    }
}